from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import action
from django.contrib import auth
from django.contrib.sessions.models import Session
from django.db.models import Q
from django.utils import timezone
from .models import User
from .serializers import UserSerializer
from .permissions import UserPermission
import re
# Create your views here.


class UserViewSet(viewsets.ModelViewSet):
    """
    list: 
    获取所有用户信息
    create: 
    创建一个用户,默认密码1234567890
    read:
    获取单个用户信息
    update:
    更新单个用户信息,需要全字段
    partial_update:
    更新单个用户信息,只需要提供的字段
    delete:
    删除单个用户信息
    """
    queryset = User.objects.order_by("-id")
    serializer_class = UserSerializer
    filterset_fields={
        "username":['exact','icontains'],
        "age":['gte','lte'],
    }
    
    def create(self, request, *args, **kwargs):
        username=request.data.get('username')
        password = request.data.get('password')
        if len(User.objects.filter(username=username))>0:
            return Response(data="用户名已经存在",status=status.HTTP_400_BAD_REQUEST)
        if password is None:
            return Response(data="空密码",status=status.HTTP_400_BAD_REQUEST)
        if re.compile(r"[0-9a-zA-Z]{6,20}").fullmatch(password) is None:
            return Response(data="密码无效",status=status.HTTP_400_BAD_REQUEST)
        response = super().create( request, *args, **kwargs)
        user=User.objects.get(username=username)
        user.set_password(password)
        user.save()
        return response
    
    def update(self, request, *args, **kwargs):
        instance:User = self.get_object()
        password = request.data.get('password')
        if password:
            if re.compile(r"[0-9a-zA-Z]{6,20}").fullmatch(password) is None:
                return Response(data="密码无效",status=status.HTTP_400_BAD_REQUEST)
            else:
                instance.set_password(password)
                instance.save()
        return super().update(request,*args,**kwargs)
    
    @action(methods=["post"],detail=False)
    def login(self,request,*args,**kwargs):
        username = request.data.get('username')
        password = request.data.get('password')
        try:
            user = User.objects.get(username=username)
        except:
            return Response(data={"msg":"用户名不存在"},status=status.HTTP_400_BAD_REQUEST)
        if User.check_password(user,password):
            return Response(data={"msg":"登录成功","user_id":user.pk},status=status.HTTP_200_OK)
        else:
            return Response(data={"msg":"登录失败"},status=status.HTTP_400_BAD_REQUEST)
        
        
        
        
        
    
    
    